<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------

namespace app\services\car;


use app\dao\car\CarTypeDao;
use app\model\car\BasePlace;
use app\model\car\CarInfo;
use app\model\car\CarOrder;
use app\model\car\CarType;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;
use crmeb\services\FormBuilder as Form;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Route as Url;

/**
 * Class CarTypeServices
 * @package app\services\shendeng
 */
class CarTypeServices extends BaseServices
{
    public function __construct(CarTypeDao $dao)
    {
        $this->dao = $dao;
    }
    /**
     * 列表
     * @param array $where
     * @param string $field
     * @param bool $is_page
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(array $where = [],string $field = '*',bool $is_page = false){
        $page = $limit = 0;
        if($is_page){
            [$page, $limit] = $this->getPageValue();
        }
        $list = $this->dao->getList($where,$field,$page,$limit);
        $count = $this->dao->count($where);
        return compact('list','count');
    }

    /**
     * 添加/修改
     * @param int $id
     * @param array $admin
     * @return array
     * @throws \FormBuilder\Exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(int $id,array $admin){
        $type = $this->dao->get($id);
        $basePlaceServices = app()->make(BasePlaceServices::class);
        $typeInfoServices = app()->make(CarTypeInfoServices::class);
        $place = $basePlaceServices->getStoreList2();
        $typeInfo = $typeInfoServices->getTypeInfoSelect();
        $field = array();
        $title = $id ? '修改' : '添加';
        $field[] = Form::hidden('id', $id);
        if($admin['store_id']){
            $field[] = Form::select('place_id', '所属门店', $admin['store_id'])->setOptions($place)->filterable(true)->disabled(true);
        }else{
            $field[] = Form::select('place_id', '所属门店', $type['place_id']??'')->setOptions($place)->filterable(true);
        }
        $field[] = Form::select('type_info_id', '所属车型', $type['type_info_id']??'')->setOptions($typeInfo)->filterable(true);
//        $field[] = Form::number('price_hour', '小时价格', $type['price_hour']??'')->style(['width'=>'100%']);
        $field[] = Form::number('price', '平日价格', $type['price']??'')->style(['width'=>'100%']);
//        $field[] = Form::number('sat_price', '周六价格', $type['sat_price']??'')->style(['width'=>'100%']);
//        $field[] = Form::number('sun_price', '周日价格', $type['sun_price']??'')->style(['width'=>'100%']);
        $field[] = Form::number('zhoumo_price', '周末价格', $type['zhoumo_price']??'')->style(['width'=>'100%']);
        $field[] = Form::number('base_service_fee', '基础服务费', $type['base_service_fee']??'')->style(['width'=>'100%']);
        $field[] = Form::number('illegal_deposit', '违章押金', $type['illegal_deposit']??'')->style(['width'=>'100%']);
        $field[] = Form::number('deposit', '车型押金', $type['deposit']??'')->style(['width'=>'100%']);
        $field[] = Form::radio('status','是否显示',$type['status']??1)->options([['label'=>'显示','value'=>1],['label'=>'隐藏','value'=>0]]);
        return create_form($title, $field, Url::buildUrl('/car/type/save'), 'POST');
    }

    /**
     * 添加/修改保存
     * @param int $id
     * @param array $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(int $id, array $data){
        $type = $this->dao->getOne(['type_info_id' => $data['type_info_id'],'place_id'=>$data['place_id'],'is_del'=>0]);
        if ($id) {
            $data['sat_price'] = $data['zhoumo_price'];
            $data['sun_price'] = $data['zhoumo_price'];
            if (!$this->dao->get($id)) throw new AdminException('数据不存在');
            if ($type && $id != $type['id']) throw new AdminException('该门店已存在车型');
            if (!$this->dao->update($id, $data)) throw new AdminException('修改失败或者您没有修改什么');
        } else {
            unset($data['id']);
            if ($type) throw new AdminException('该门店已存在车型');
            $data['add_time'] = time();
            if (!$this->dao->save($data)) throw new AdminException('添加失败');
        }
        return true;
    }

    /**
     * 删除
     * @param int $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delType(int $id){
        $type = $this->dao->get($id);
        $this->check($type,"dianpu");
        if ($type) {
            $data['is_del'] = 1;
            $data['delete_time'] = time();
            if (!$this->dao->update($id,$data)) throw new AdminException('删除失败,请稍候再试!');
        }
        return '删除成功!';
    }

    /**
     * 显示/隐藏
     * @param int $id
     * @param int $status
     * @param $type
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setShow(int $id, int $status,$type){
        $typeInfo = $this->dao->getOne(['id' => $id,'is_del'=>0]);
        if (!$typeInfo) throw new AdminException('数据不存在');
        if($type == 'status'){
            if ($this->dao->update($id, ['status' => $status])) {
                return $status == 1 ? '显示成功' : '隐藏成功';
            } else {
                throw new AdminException($status == 1 ? '显示失败' : '隐藏失败');
            }
        }elseif($type == 'is_hot'){
            if ($this->dao->update($id, ['is_hot' => $status])) {
                return $status == 1 ? '热销成功' : '不热销成功';
            } else {
                throw new AdminException($status == 1 ? '热销失败' : '不热销失败');
            }
        }elseif($type == 'is_recommend'){
            if ($this->dao->update($id, ['is_recommend' => $status])) {
                return $status == 1 ? '推荐成功' : '不推荐成功';
            } else {
                throw new AdminException($status == 1 ? '推荐失败' : '不推荐失败');
            }
        }
    }

    /**
     * 车型下拉列表
     * @param array $where
     * @param string $field
     * @param bool $is_page
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTypeList(array $where = [],string $field = '*',bool $is_page = false){
        $page = $limit = 0;
        if($is_page){
            [$page, $limit] = $this->getPageValue();
        }
        $list = $this->dao->getList($where,$field,$page,$limit);
        $type = array();
        foreach ($list as $key => $item){
            $type[$key]['value'] = $item['id'];
            $type[$key]['label'] = $item['type_name'];
        }
        $count = $this->dao->count($where);
        return compact('type','count');
    }

    /**
     * 车型关联的门店
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getType($where){
        $where['is_del'] = 0;
        $list = $this->dao->getType($where);
        $type = [];
        foreach ($list as $item){
            if($item['title'] && $item['type_name']){
                $type[] = ['value'=>$item['id'],'label'=>$item['title'].' -- '.$item['type_name']];
            }
        }
        return $type;
    }

    /**
     * 获取门店车辆
     * @param $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCityTypeList($where){
        $list = [];
//        $long_km = get_distance($where['take_latitude'],$where['take_longitude'],$where['return_latitude'],$where['return_longitude'],2);
        // 通过城市ID获取该城市所有门店
        $place = BasePlace::alias('p')->field('p.id')
//            ->join('base_send_fee f','p.id=f.store_id','left') //注释2023年11月29日10:31:42  上门取还车用
            ->where(['p.city_id'=>$where['city_id'],'p.is_del'=>0,'p.place_type'=>0])
//            ->where('f.mink_km','<=',$long_km)->where('f.max_km','>',$long_km) //注释2023年11月29日10:31:42  上门取还车用
            ->select()->toArray();
        if(!$place) return compact('list');
        $temp = [];
        foreach ($place as $place_item){
            $temp[] = $place_item['id'];
        }
        if(!$temp) throw new ValidateException('该城市暂未设置门店');
//        $place_id = join(',',$temp);
        [$page,$limit] = $this->getPageValue();
//        $where['place_id'] = $place_id; //注释2023年11月29日10:31:42
        $where['status'] = 1;//查询状态为显示的
        $list = $this->dao->getCityTypeList($where,$page,$limit);
        foreach ($list as &$type_item){
            $type_item['gear'] = $type_item['gear'] == 'auto' ? '自动挡' : '手动挡';
            $type_item['price'] = $type_item['price'] - 0;
            // 计算每种车的总价
            $type_item['total_prices'] = $type_item['price'];
        }
        foreach($list as $k=>$v){
            //查询该车型下面的车有没有上架的
            $car_info = Db::name('car_info')->field('car_no,type_id,car_status,sxj_status')->where('type_id',$v['type_id'])->select()->toArray();
            //查询该车型下面是否有车辆可租
            $carInfoServices = app()->make(CarInfoServices::class);
            $car_info2 = $carInfoServices->getCarInventory($v['type_id'],$where['stat_stamp'],$where['end_stamp']);
            $car_list = $car_info2['car_list'];
            $is_x = 2;//没有
            foreach($car_info as$kk=>$vv){
                if($vv['car_status']==1&&$vv['sxj_status']==1&&$car_list){
                    $is_x = 1;
                }
            }
            if($is_x==2){
                unset($list[$k]);
            }
            unset($is_x);
        }
        $list = array_values($list);
        return compact('list');
    }

    /**
     * 获取车辆信息
     */
    public function getCarInfo($where){
        $info = Db::name('car_type')->alias('c')
            ->leftJoin('car_type_info i','i.id = c.type_info_id')
            ->leftJoin('base_place p','p.id = c.place_id')
            ->field('c.*,i.*,p.title as place_title,p.poiaddress as place_poiaddress')
            ->where(['c.id'=>$where['car_type_id'],'i.is_del'=>0])
            ->find();
        if(!$info){
            $info = [];
        }
        if($info['gear']=="hand"){
            $info['gear'] = "手动挡";
        }else{
            $info['gear'] = "自动挡";
        }
        return $info;

    }
    /**
     * 获取车辆信息2
     */
    public function getCarInfo2($where){
        $info = Db::name('car_type')->alias('c')
            ->leftJoin('car_type_info i','i.id = c.type_info_id')
            ->leftJoin('base_place p','p.id = c.place_id')
            ->field('c.*,i.*,p.title as place_title,p.poiaddress as place_poiaddress')
            ->where(['c.type_info_id'=>$where['car_type_id'],'c.place_id'=>$where['place_id'],'i.is_del'=>0])
            ->find();
        if(!$info){
            $info = [];
        }
        return $info;

    }


    /**
     * 排车
     * @param $data
     * @return array|mixed|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function platoonCar($data){
        // 店铺下对应车型的车辆
        $car = CarInfo::field('id,car_no')->where(['type_id'=>$data['type_id'],'is_del'=>0,'status'=>1,'car_status'=>1,'sxj_status'=>1])->select()->toArray();
        if(!$car) return $car;
        //查询自动排车的车辆
        $auto_car = Db::name('car_occupy_time')->where('order_id',$data['order_id'])->value('id');
        $list = [];
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        /** @var CarOccupyTimeServices $occupyServices */
        $occupyServices = app()->make(CarOccupyTimeServices::class);
        foreach ($car as $item){ // 获取未被占用的车辆
            if(!$occupyServices->isOccupy($item['id'],$data['start_time'],$data['end_time'],$auto_car)) $list[] = $item;
        }
        return $list;
    }

    /**
     * 门店车型
     * @param int $place_id
     * @return mixed
     */
    public function storeCar(int $place_id){
        $type = CarType::alias('t')
            ->join('car_type_info i','i.id=t.type_info_id','left')
            ->join('car_category c','c.id=i.cate_id','left')
            ->field('t.id,i.type_name,i.pic,i.power,i.gear,i.seat_num,c.cate_name,t.price')
            ->where(['t.is_del'=>0,'t.place_id'=>$place_id,'t.status'=>1])
            ->select()->toArray();
        foreach ($type as &$item){
            $item['gear'] = $item['gear']=='auto' ? '自动挡' : '手动挡';
        }
        return $type;
    }

    /**
     * 换车保存
     * @param array $data
     * @param array $op_user
     * @param int $op_user_type
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeSaveCar(array $data,array $op_user,int $op_user_type){
        $orderInfo = CarOrder::find($data['order_id']);
        $orderInfo = $orderInfo ? $orderInfo->toArray() : [];
        if(!$orderInfo) throw new ValidateException('未查询到订单信息');
        $update = [
            'type_id'=>$data['type_id'],
            'type_name'=>$data['type_name'],
            'type_pic'=>$data['pic'],
            'type_price'=>$data['price'],
        ];
        if(CarOrder::where(['id'=>$data['order_id']])->update($update)){
            $title = '订单换车为【'.$data['type_name'].'】';
            BaseLogServices::addLog($data['order_id'],2,$title,$op_user_type,$op_user['id'],$op_user['user_name'],18);
            return '换车成功';
        }else{
            throw new ValidateException('换车失败');
        }
    }
}
